package net.cl.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.cl.Provider;

public class HtmlUtil {

	public static final String JS_PATTERN = "<\\s*script[^>]*>.*?<\\s*/script[^>]*>";
	public static final String TAG_PATTERN = "<[^>]*>";
	public static final String IMG_SRC_PATTERN = "<\\s*img\\s+.*?src\\s*=\\s*[\\\"|']([^\\\"|^']*)[^>]*>";

	/**
	 * 如果内容中有类似"&amp;#187;"的字符，转义成其原始字符
	 */
	public static String unEscapeHtmlNumber(String input) {
		if (input == null)
			return StringUtil.NULL;
		input = input.replace("&#36;", "$").replace("&#92;", "\\");
		Pattern p1 = Pattern.compile("&#(\\d{1,});");
		Matcher m1 = p1.matcher(input);
		StringBuffer sb = new StringBuffer();
		char c;
		while (m1.find()) {
			c = (char) Integer.parseInt(m1.group(1));
			m1.appendReplacement(sb, String.valueOf(c));
		}
		m1.appendTail(sb);
		return sb.toString();
	}

	/**
	 * 过滤全部javascript标签,即<code>&lt;script&gt;&lt;/script&gt;</code>以内的所有内容
	 */
	public static String stripScriptTag(String input) {
		return input == null ? "" : input.replaceAll("(?si)" + JS_PATTERN, "");
	}

	/**
	 * 过滤全部html标签,即<code>&lt;&gt;</code>以内的所有内容
	 */
	public static String stripTags(String input) {
		return input == null ? "" : input.replaceAll(TAG_PATTERN, "");
	}

	/**
	 * 转码html特殊字符
	 */
	public static String escapeHTML(String input) {
		return input == null ? "" : input.replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;")
				.replace("'", "`");
	}

	/**
	 * 解码html特殊字符
	 */
	public static String unescapeHTML(String input) {
		return input == null ? "" : input.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"");
	}

	public static List<String> getImg(String input) {
		Matcher matcher = Provider.getPattern(IMG_SRC_PATTERN).matcher(input);
		List<String> list = new ArrayList<String>();
		while (matcher.find()) {
			list.add(matcher.group(1));
		}
		return list;
	}

}
